package com.wushi.lenovo.asia5b.wxapi;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.mvp.utils.JsonUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wushi.lenovo.asia5b.app_model.other.WXLoginModel;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;

/**
 * Created by zhangyuncai on 2020/6/22.
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private WXEntryActivity mActivity;
    //    "wxeb9cbbdcf7846c37", "e44a92a991add73d13a60ca269e57a81"
    private final static String APP_ID = "wxeb9cbbdcf7846c37";
    private final static String WECHAT_SCRECT = "e44a92a991add73d13a60ca269e57a81";
    private IWXAPI wxapi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mActivity = this;
        super.onCreate(savedInstanceState);

//        getSupportActionBar().hide();
//        // 隐藏状态栏
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        wxapi = WXAPIFactory.createWXAPI(this, APP_ID, true);
        wxapi.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        wxapi.handleIntent(intent, WXEntryActivity.this);//必须调用此句话
    }


    @Override
    public void onReq(BaseReq baseReq) {

    }


    //请求回调结果处理
    @Override
    public void onResp(BaseResp baseResp) {
//登录回调
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) baseResp).code;
                //获取accesstoken
                getAccessToken(code);
                Log.d("fantasychongwxlogin", code.toString() + "");
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                finish();
                break;
            default:
                finish();
                break;
        }
    }


    private void getAccessToken(String code) {
        createProgressDialog();
        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append(APP_ID)
                .append("&secret=")
                .append(WECHAT_SCRECT)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        Log.d("urlurl", loginUrl.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(loginUrl.toString())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("fan12", "onFailure: ");
                mProgressDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo = response.body().string();
                Log.d("fan12", "onResponse: " + responseInfo);
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                getUserInfo(access, openId);
            }
        });
    }

    ProgressDialog mProgressDialog;

    private void createProgressDialog() {
        mProgressDialog = new ProgressDialog(mActivity);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//转盘
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("提示");
        mProgressDialog.setMessage("登录中，请稍后");
        mProgressDialog.show();
    }

    private void getUserInfo(String access, String openid) {
        String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openid;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(getUserInfoUrl)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("fan12", "onFailure: ");
                mProgressDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseInfo = response.body().string();
                    Timber.d("--->>>>>>>>---responseInfo:" + responseInfo);
                    WXLoginModel wxLoginModel = JsonUtil.INSTANCE.jsonToAny(responseInfo, WXLoginModel.class);
                    EventBus.getDefault().post(new WXLoginEvent(wxLoginModel));

                } catch (Exception e) {
                    e.printStackTrace();
                }
//                {"openid":"o_XLLt9x0ZwBkgdu_VLXy0_skKLU","nickname":"张运才","sex":1,"language":"zh_CN","city":"Guangzhou","province":"Guangdong","country":"CN","headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/MdGkWqia0EzQfTYVvw43lq4MukiayVgjcmQ4OPdicddDwTHTjYtwPsTm4KjODyQGow1bxnBJEgB7oTPDbJYiaxKibLA\/132","privilege":[],"unionid":"oC7jGwm53mX6X1ys3O0lrsxHbkMc"}
                finish();
                mProgressDialog.dismiss();
            }
        });
    }
}
